package com.cs.study.homework._0309.test;

import com.cs.study.homework.utils.NetworkUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

//定义发送任务 SendTask 专门用来发送消息
public class ReceiveTask implements Runnable {
    //    定义成员变量
    DatagramSocket datagramSocket;

    //    定义接收任务 receiveTask  专门用来接收消息
    public ReceiveTask(DatagramSocket datagramSocket) {
        this.datagramSocket = datagramSocket;
    }

    @Override
    public void run() {
        while (true) {
            // 创建用于接收的数据报包
            DatagramPacket receivePacket = NetworkUtils.getReceivePacket();
            try {
                // receive接收
                datagramSocket.receive(receivePacket);
                //解析
                String msg = NetworkUtils.parseMsg(receivePacket);
                //打印
                System.out.println("收到了来自" + receivePacket.getSocketAddress() + "的消息：" + msg);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
